/*
 * Copyright 2007-2010 Sun Microsystems, Inc.
 *
 * This file is part of Project Darkstar Server.
 *
 * Project Darkstar Server is free software: you can redistribute it
 * and/or modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation and
 * distributed hereunder to you.
 *
 * Project Darkstar Server is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * --
 */

package com.gzy.gameserver;

import java.io.Serializable;
import java.util.Properties;
import java.util.logging.Logger;
import java.util.logging.Level;

import com.sun.sgs.app.*;

/**
 * Hello World example for the Project Darkstar Server.
 * Prints {@code "Hello World!"} to the console the first time it is started.
 */
public class GameServer
    implements AppListener, // to get called during application startup.
               Serializable // since all AppListeners are ManagedObjects.
{
    /** The version of the serialized form of this class. */
    private static final long serialVersionUID = 1L;
    
    /**The{@linkLogger}forthisclass.*/
    private static final Logger logger =
    Logger.getLogger(GameServer.class.getName());
    
    private ManagedReference<World> worldRef = null;
    
    /**
     * {@inheritDoc}
     * <p>
     * Prints our well-known greeting during application startup.
     */
    public void initialize(Properties props) 
    {
    	logger.info("Game Server Initialize ...");
    	World world = new World("Game World", "The game world", 2);
    	
    	world.initialze(props);
    	setWorld(world);
    	
    	logger.info("Game Server Initialized !");
    }

    public World getWorld()
    {
    	if (worldRef == null)
    		return null;
    	return worldRef.get();
    }
    
    public void setWorld(World world)
    {
		DataManager dataMgr = AppContext.getDataManager();
		
		if (world == null)
		{
			this.worldRef = null;
			return;
		}
		this.worldRef = dataMgr.createReference(world);
    }
    /**
     * {@inheritDoc}
     * <p>
     * Prevents client logins by returning {@code null}.
     */
    public ClientSessionListener loggedIn(ClientSession session) {
    	logger.log(Level.INFO, "User {0} has logged in", session.getName());
    	Player player = Player.loggedIn(session);
    	player.setWorld(getWorld());
    	
        return player;
    }
}
